package ls

import (
	"fmt"
	"strings"

	"gitee.com/eeppee_admin/go-tuiftp/reuse"
	"github.com/jlaffaye/ftp"
)

// Rls 递归列出FTP目录内容
func Rls(path string) error {
	// 解析路径格式
	arr := strings.Split(path, ":")
	if len(arr) != 2 {
		return fmt.Errorf("远程路径格式错误, 正确格式: [站点名称]:[远程路径]")
	}
	siteName, remotePath := arr[0], arr[1]

	// 读取配置
	sysConfig := &reuse.SysConfig{}
	if err := sysConfig.Read(); err != nil {
		return fmt.Errorf("读取配置失败: %v", err)
	}

	var targetSite *reuse.SiteConfig
	for _, site := range sysConfig.Sites {
		if site.Name == siteName {
			s := site
			targetSite = &s
			break
		}
	}

	if targetSite == nil {
		return fmt.Errorf("未找到站点: %s", siteName)
	}

	// 连接FTP
	ftpClient, err := reuse.NewFtpClient(*targetSite)
	if err != nil {
		return fmt.Errorf("连接FTP失败: %v", err)
	}
	defer ftpClient.Conn.Quit()

	// 开始递归列出
	fmt.Printf("递归列出 %s:%s 内容:\n", siteName, remotePath)
	return listRecursive(ftpClient, remotePath, 0)
}

// 递归列出目录内容
func listRecursive(client *reuse.FtpClient, path string, depth int) error {
	entries, err := client.Conn.List(path)
	if err != nil {
		return fmt.Errorf("列出目录 %s 失败: %v", path, err)
	}

	indent := strings.Repeat("  ", depth)
	for _, entry := range entries {
		// 跳过.和..
		if entry.Name == "." || entry.Name == ".." {
			continue
		}

		fmt.Printf("%s%s %-10s %-15s %s\n",
			indent,
			reuse.If(entry.Type == ftp.EntryTypeFolder, "文件夹", "文件"),
			reuse.HumanReadableSize(entry.Size),
			entry.Time.Format("2006-01-02"),
			entry.Name)

		// 如果是目录，递归处理
		if entry.Type == ftp.EntryTypeFolder {
			newPath := path
			if newPath[len(newPath)-1] != '/' {
				newPath += "/"
			}
			newPath += entry.Name

			if err := listRecursive(client, newPath, depth+1); err != nil {
				return err
			}
		}
	}

	return nil
}
